package com.fengniao.goods.controller;

import com.fengniao.goods.pojo.Spec;
import com.fengniao.goods.service.SpecService;
import com.github.pagehelper.PageInfo;
import entity.DBOperUtil;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author lanhai
 * @date 2021/7/5 16:41
 */
@RestController
@RequestMapping("/spec")
@CrossOrigin
public class SpecController {

    @Autowired
    private SpecService specService;

    /**
     * 根据分类ID查询规格信息
     * @param categoryId
     * @return
     */
    @GetMapping("/category/{categoryId}")
    public Result<List<Spec>> findByCategoryId(@PathVariable Integer categoryId) {
        List<Spec> specs = specService.findByCategoryId(categoryId);
        return Result.data(specs);
    }

    @GetMapping
    public Result<List<Spec>> findAll() {
        List<Spec> all = specService.findAll();
        return Result.data(all);
    }

    @GetMapping("/{id}")
    public Result<Spec> findById(@PathVariable Integer id) {

        return Result.data(specService.findById(id));
    }

    @PostMapping
    public Result add(@RequestBody Spec spec) {

        int flag = specService.add(spec);
        DBOperUtil.checkDBOper(flag, "添加规格失败");
        return Result.ok("添加规格成功");
    }

    @PutMapping("/{id}")
    public Result revise(@PathVariable Integer id, @RequestBody Spec spec) {

        spec.setId(id);
        int flag = specService.revise(spec);
        DBOperUtil.checkDBOper(flag, "添加规格失败");
        return Result.ok("修改规格成功");
    }

    @DeleteMapping("/{id}")
    public Result remove(@PathVariable Integer id) {

        int flag = specService.remove(id);
        DBOperUtil.checkDBOper(flag,"删除规格失败");
        return Result.ok("删除规格成功");
    }

    @PostMapping("/search")
    public Result<List<Spec>> findList(@RequestBody Spec spec) {

        List<Spec> list = specService.findList(spec);
        return Result.data(list);
    }

    @GetMapping("/search/{num}/{size}")
    public Result<PageInfo<Spec>> findPage(@PathVariable("num") Integer num,
                                            @PathVariable("size") Integer size) {

        PageInfo<Spec> page = specService.findPage(num, size);
        return Result.data(page);
    }

    @PostMapping("/search/{num}/{size}")
    public Result<PageInfo<Spec>> findPage(@RequestBody(required = false) Spec spec,
                                            @PathVariable("num") Integer num,
                                            @PathVariable("size") Integer size) {

        PageInfo<Spec> page = specService.findPage(spec, num, size);
        return Result.data(page);
    }
}
